package com.ruoyi.common.utils.baidu;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

public class RestTemplateWithTrustAllCerts {

    public static RestTemplate createRestTemplateWithTrustAllCerts() throws NoSuchAlgorithmException, KeyManagementException {
        // 创建信任所有证书的SSLContext
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[]{new TrustAllCertsManager()}, new java.security.SecureRandom());

        // 创建SSLSocketFactory
        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();

        // 使用Apache HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(new SSLConnectionSocketFactory(sslSocketFactory, (hostname, session) -> true))
                .build();

        // 创建HttpComponentsClientHttpRequestFactory并设置httpClient
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        // 创建RestTemplate并设置requestFactory
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        return restTemplate;
    }
}
